package com.sloan.community.util;


import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.sloan.community.common.Constant.*;

public class TextUtils {

    // 高亮词左右需要取的字符
    private final static Integer LEFT_N = 30;
    private final static Integer RIGHT_N = 30;

    public final static Integer TEXT_NUM = 100;

    public final static String SUFFIX = "...";

    public static final String HIGH_LIGHT = "<strong style='color:red'>%s</strong>";


    public static String handleImgHtmlToText(String htmlText, Integer len) {
        if (!StringUtils.hasText(htmlText)) {
            return htmlText;
        }

        String replyText = htmlText.replaceAll(IMG_TAG, IMG_TEXT);
        int length = replyText.length();
        if (len.equals(length)) {
            return replyText;
        } else {
            int i = replyText.indexOf(IMG_TEXT);
            if (i == -1 || i <= len - IMG_TEXT.length() || i >= len) {
                return replyText.substring(0, Math.min(len, length)) + SUFFIX;
            } else {
                return replyText.substring(0, Math.min(i + IMG_TEXT.length(), length)) + SUFFIX;
            }
        }
    }


//    public static String toHtml(String content){
//        // 创建 Markdown 解析器配置
//        MutableDataSet options = new MutableDataSet();
//        options.set(Parser.EXTENSIONS, Arrays.asList(
//                TablesExtension.create(),
//                StrikethroughExtension.create()
//        ));
//
//        // 创建解析器
//        Parser parser = Parser.builder(options).build();
//
//        // 解析 Markdown 内容
//        Node document = parser.parse(content);
//
//        // 创建 HTML 渲染器
//        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
//
//        // 将解析后的内容渲染为 HTML
//        return renderer.render(document);
//    }


    /**
     * 采用滑动窗口&合并区间算法来替换高亮词
     *
     * @param text
     * @param keyword
     * @return
     */
    public static String highlightText(String text, String keyword, Integer num) {
        if (!StringUtils.hasText(text)) {
            return "";
        }

        String resText = text.substring(0, Math.min(text.length(), TEXT_NUM)) + "...";
        if (keyword == null || keyword.isEmpty()) {
            return resText;
        }

        List<Boundary> boundaries = getBoundaryIndex(text, keyword);

        int size = boundaries.size();
        if (size == 0) {
            return resText;
        }

        List<Boundary> res = mergeBoundaryIndex(boundaries);

        StringBuilder sb = new StringBuilder();
        for (Boundary bd : res) {
            sb.append(text, bd.left, bd.right + 1);
            if (sb.length() >= num) {
                break;
            }
        }

        return sb.append("...")
                .toString()
                .replace(keyword, String.format(HIGH_LIGHT, keyword));
    }

    public static List<Boundary> getBoundaryIndex(String text, String keyword) {
        List<Boundary> boundaries = new ArrayList<>();

        int tLen = text.length();
        int keyLen = keyword.length();
        char keyFirstC = keyword.charAt(0);

        int i = 0;
        while (i <= tLen - keyLen) {
            char tC = text.charAt(i);
            if (keyFirstC != tC) {
                i++;
                continue;
            }

            int j = 1;
            boolean find = true;
            while (j < keyLen) {
                if (keyword.charAt(j) != text.charAt(i + j)) {
                    find = false;
                    break;
                }
                j++;
            }

            if (!find) {
                i++;
            } else {
                int left = i;
                int right = i + keyLen - 1;
                int maxLeft = Math.max(left - LEFT_N, 0);
                int minRight = Math.min(right + RIGHT_N, text.length() - 1);
                boundaries.add(new Boundary(maxLeft, minRight));
                i = i + keyLen;
            }
        }
        return boundaries;
    }

    public static List<Boundary> mergeBoundaryIndex(List<Boundary> boundaries) {
        if (boundaries == null || boundaries.isEmpty()) {
            return boundaries;
        }

        List<Boundary> res = new ArrayList<>();

        Boundary last = boundaries.get(0);
        res.add(last);

        int idx = 1;
        int size = boundaries.size();
        while (idx < size) {
            Boundary cur = boundaries.get(idx);
            if (cur.left <= last.right) {
                res.remove(last);
                Boundary boundary = new Boundary(last.left, cur.right);
                res.add(boundary);
                last = boundary;
            } else {
                res.add(cur);
                last = cur;
            }
            idx++;
        }

        return res;
    }


    public static class Boundary {
        public int left;
        public int right;

        public Boundary(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }


    public static void main(String[] args) {
        /**
         * 下标:  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
         * 字符:  0  0  A  B  C  0  0  A  B  C  0  0  0  0  A  B  D  0  0  0  0  A  B  C  0  A  B
         */
        String text = "00ABC00000000000000ABC0000ABD0000ABC0AB";
        String keyword = "ABC";
        System.out.println(highlightText(text, keyword, 10));
    }

    public static void test1() {

    }


    public static class Index {
        public int left;
        public int right;

        public Index(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }
}
